/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.text.DecimalFormat;
import javax.swing.JSpinner;
import se.chalmers.ait.dat215.project.ShoppingItem;

/**
 *
 * @author Gustav
 */
public class ShoppingItemPresenter {
    private ShoppingItemView shoppingItemView;
    private ShoppingItem shoppingItem;
    private DecimalFormat nf = new DecimalFormat();

    public ShoppingItemPresenter (ShoppingItemView view) {
        this.shoppingItemView = view;
        nf.setMinimumFractionDigits(2);
    }

    public void setShoppingItem(ShoppingItem item) {



        this.shoppingItem = item;
        String name = shoppingItem.getProduct().getName();
        String price = nf.format(shoppingItem.getTotal())+" kr";
        shoppingItemView.getProductNameLabel().setText(name);
        shoppingItemView.getProductNameLabel().setToolTipText(shoppingItem.getProduct().getName());
        shoppingItemView.getProductPriceLabel().setText(price);
        shoppingItemView.getAmountSpinner().setValue(shoppingItem.getAmount());

        shoppingItemView.getAmountSpinner().setEditor(
                    new JSpinner.NumberEditor(shoppingItemView.getAmountSpinner(),
                    "0 "+shoppingItem.getProduct().getUnitSuffix())
                );
    }

    void valueChanged(double amount) {
        shoppingItem.setAmount(amount);

        if (amount <= 0) {
            removeItem();
        }
        String text = "<html>"+shoppingItem.getProduct().getName()+"<br>"+nf.format(shoppingItem.getTotal())+" kr";
        shoppingItemView.getProductNameLabel().setText(text);
        DataHandler.getInstance().getMainWindow().getCheckoutView().updateReceipt();
    }

    public void removeItem() {
        DataHandler.getInstance().getShoppingCart().removeItem(shoppingItem);
        DataHandler.getInstance().getMainWindow().getCheckoutView().updateReceipt();
    }

}
